package com.micro.frog.acct.utils;


import com.micro.frog.core.contants.MaGlobal;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 服务器端 Cookie 工具类
 *
 * @author :  ljh
 * @date : 2018/4/10
 **/
public class CookieUtil {

    //通过cookie获取token
    public static String getToken(HttpServletRequest request) {
        return getValue(request, MaGlobal.COOKIE_TOKEN);
    }

    public static String createToken(HttpServletResponse response) {
        String token = MaGlobal.randomUUID();
        addCookie(response, MaGlobal.COOKIE_TOKEN, token , MaGlobal.Cookie_Expire_Time);
        return token;
    }

    //刷新cookie时效
    public static void refreshToken(HttpServletRequest request, HttpServletResponse response, int expireTime) {
        addCookie(response, MaGlobal.COOKIE_TOKEN, getToken(request), expireTime);
    }

    public static void addCookie(HttpServletResponse response, String cookeName, String cookieValue, Integer maxAge) {
        addCookie(response, cookeName, cookieValue, maxAge, null, null);
    }

    public static void addCookie(HttpServletResponse response,
                                 String cookeName, String cookieValue, Integer maxAge,
                                 String domain, String path) {
        Cookie cookie = new Cookie(cookeName, cookieValue);
        //时效
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        //访问域 默认当前根域 :（www.baidu.com/index 即：只对www.baidu.com/index有用）
        if (!StringUtils.isEmpty(domain)) {
            cookie.setDomain(domain);
        }
        //存放路径 默认根路径
        cookie.setPath(StringUtils.isEmpty(path) ? "/" : path);

        response.addCookie(cookie);
    }


    public static String getValue(HttpServletRequest request, String key) {

        Cookie cookie = null;

        Cookie[] cookies = request.getCookies();

        if (cookies != null){
            for (Cookie c : cookies) {
                if (key.equals(c.getName())) {
                    cookie = c;
                    break;
                }
            }
        }
        return cookie != null ? cookie.getValue() : "";
    }
}
